# -*- coding:utf-8 -*-
# !/usr/bin/python

from __future__ import print_function

import os
import re 
import sys
import time
import datetime
import argparse
import binascii
import ctypes
import serial

import numpy as np 
from scipy import signal
from matplotlib import pyplot as plt     
from matplotlib import animation    

ll = []
lo = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
ld = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
le = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
la = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
displen = 100

def to_str(data):
    if isinstance(data,bytes):
        #value = data.decode('utf-8')
        value = ''.join([('%c'%d) for d in data])
    else:
        value = data
    return value

def read_data():

    for i in range(0,10):
        nr = to_str(ser.readline())
        if len(ll):
            print(nr,end='')

        if "SENSOR_DESCRIPTORS" in nr:
            ch = nr.split()
            for cch in ch:
                if 'CS0' in cch:
                    ll.append(int(cch.split('.')[-1])) 
                elif 'CS1' in cch:
                    ll.append(8+int(cch.split('.')[-1])) 
            nr = to_str(ser.readline())
            nr = to_str(ser.readline())

        else:
            ldd = nr.split()
            lll = len(ll)
            try:
                for i in range(0,lll):
                    la[ll[i]] = ll[i]
                    lo[ll[i]].append(int(ldd[i]))
                    ld[ll[i]].append(int(ldd[lll+i]))
                    le[ll[i]].append(lo[ll[i]][-1]+int(ldd[lll*4+i]))
            except BaseException,e:
                print(e.message)
                continue

    lll = len(ll)
    if len(ld[0]) > displen:
        for i in range(0,lll):
            lo[ll[i]] = lo[ll[i]][-displen:]
            ld[ll[i]] = ld[ll[i]][-displen:]
            le[ll[i]] = le[ll[i]][-displen:]

    if len(ll) == 0:
        print("Please reset device!")

    return lo,ld,le,la
        
def init():    
    line = [line1,line2,line3,line4,line5,line6,line7,line8,line9,line10,line11,line12,line13,line14,line15,line16]
    base = [base1,base2,base3,base4,base5,base6,base7,base8,base9,base10,base11,base12,base13,base14,base15,base16]
    eff = [eff1,eff2,eff3,eff4,eff5,eff6,eff7,eff8,eff9,eff10,eff11,eff12,eff13,eff14,eff15,eff16]
    for i in range(0,16):
        line[i].set_data([], [])    
        base[i].set_data([], [])    
        eff[i].set_data([], [])    

    return line+base+eff

def animate(i):  
    line = [line1,line2,line3,line4,line5,line6,line7,line8,line9,line10,line11,line12,line13,line14,line15,line16]
    base = [base1,base2,base3,base4,base5,base6,base7,base8,base9,base10,base11,base12,base13,base14,base15,base16]
    eff = [eff1,eff2,eff3,eff4,eff5,eff6,eff7,eff8,eff9,eff10,eff11,eff12,eff13,eff14,eff15,eff16]
    lo,ld,le,la = read_data()

    for i in range(0,16):
        if i == la[i]:
            y = np.array(ld[i])     
            x = np.linspace(0,len(y),len(y))
            line[i].set_data(x, y)        

            y = np.array(lo[i])     
            x = np.linspace(0,len(y),len(y))
            base[i].set_data(x, y)        
  
            y = np.array(le[i])     
            x = np.linspace(0,len(y),len(y))
            eff[i].set_data(x, y)        
  
    return line+base+eff
  

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description = "EFM8SB10F CAP TOUCH PAD/KEY TOOLS")
    parser.add_argument('-p', dest = 'serial', help = 'serial port',required = True)
    parser.add_argument('-b', dest = 'baud', help = 'serial baud',type = int,default = 115200)
    parser.add_argument('-m', dest = 'fromat', help = 'display style[0、1]',type = int,default = 0)
    parser.add_argument('-s', dest = 'save', help = 'save log file',type = bool,default = False)
    parser.add_argument('-xmax', dest = 'xmax', help = 'x axis max value',type = int,default = 100)
    parser.add_argument('-ymax', dest = 'ymax', help = 'y axis max value',type = int,default = 13000)
    parser.add_argument('-ymin', dest = 'ymin', help = 'y axis min value',type = int,default = 10000)
    parser.add_argument('-figl', dest = 'figl', help = 'fig len',type = int,default = 15)
    parser.add_argument('-figh', dest = 'figh', help = 'fig hight',type = int,default = 10)
    args = parser.parse_args()
    
    ser = serial.Serial(args.serial,args.baud,timeout=0.05)

    displen = args.xmax
    fig = plt.figure('EFM8SB10 CAP TOUCH PAD/KEY TOOLS',figsize=(args.figl,args.figh))   
    ax1 = fig.add_subplot(1,1,1,xlim=(0, args.xmax), ylim=(args.ymin,args.ymax))  

    line1,  = ax1.plot([], [], lw=1,label='CS0')    
    line2,  = ax1.plot([], [], lw=1,label='CS1')    
    line3,  = ax1.plot([], [], lw=1,label='CS2')    
    line4,  = ax1.plot([], [], lw=1,label='CS3')    
    line5,  = ax1.plot([], [], lw=1,label='CS4')    
    line6,  = ax1.plot([], [], lw=1,label='CS5')    
    line7,  = ax1.plot([], [], lw=1,label='CS6')    
    line8,  = ax1.plot([], [], lw=1,label='CS7')    
    line9,  = ax1.plot([], [], lw=1,label='CS8')    
    line10, = ax1.plot([], [], lw=1,label='CS9')    
    line11, = ax1.plot([], [], lw=1,label='CS10')    
    line12, = ax1.plot([], [], lw=1,label='CS11')    
    line13, = ax1.plot([], [], lw=1,label='CS12')    
    line14, = ax1.plot([], [], lw=1,label='CS13')    
    line15, = ax1.plot([], [], lw=1,label='CS14')    
    line16, = ax1.plot([], [], lw=1,label='CS15')    

    base1,  = ax1.plot([], [], lw=3)    
    base2,  = ax1.plot([], [], lw=3)    
    base3,  = ax1.plot([], [], lw=3)    
    base4,  = ax1.plot([], [], lw=3)    
    base5,  = ax1.plot([], [], lw=3)    
    base6,  = ax1.plot([], [], lw=3)    
    base7,  = ax1.plot([], [], lw=3)    
    base8,  = ax1.plot([], [], lw=3)    
    base9,  = ax1.plot([], [], lw=3)    
    base10, = ax1.plot([], [], lw=3)    
    base11, = ax1.plot([], [], lw=3)    
    base12, = ax1.plot([], [], lw=3)    
    base13, = ax1.plot([], [], lw=3)    
    base14, = ax1.plot([], [], lw=3)    
    base15, = ax1.plot([], [], lw=3)    
    base16, = ax1.plot([], [], lw=3)    

    eff1,  = ax1.plot([], [], lw=2)    
    eff2,  = ax1.plot([], [], lw=2)    
    eff3,  = ax1.plot([], [], lw=2)    
    eff4,  = ax1.plot([], [], lw=2)    
    eff5,  = ax1.plot([], [], lw=2)    
    eff6,  = ax1.plot([], [], lw=2)    
    eff7,  = ax1.plot([], [], lw=2)    
    eff8,  = ax1.plot([], [], lw=2)    
    eff9,  = ax1.plot([], [], lw=2)    
    eff10, = ax1.plot([], [], lw=2)    
    eff11, = ax1.plot([], [], lw=2)    
    eff12, = ax1.plot([], [], lw=2)    
    eff13, = ax1.plot([], [], lw=2)    
    eff14, = ax1.plot([], [], lw=2)    
    eff15, = ax1.plot([], [], lw=2)    
    eff16, = ax1.plot([], [], lw=2)    

    plt.xlabel('time')
    plt.ylabel('cap value')
    plt.title('real time domain graph')

    ax1.grid(which='both', axis='both')
    ax1.legend(loc='upper left')

    anim1 = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=2)    
    plt.show()

    ser.close()
    exit()

